<template>
  <!--弹窗-->
  <el-dialog :title="title" :visible.sync="visible" :before-close="handleClose" width="380px">
    <el-form :rules="rules" ref="formData" :model="formData" label-width="100px" style="width: 300px">
      <el-form-item label="新密码：" prop="newPassword">
        <el-input type="password" placeholder="请输入新密码" v-model="formData.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码：" prop="repPassword">
        <el-input type="password" placeholder="请输入确认密码" v-model="formData.repPassword"></el-input>
      </el-form-item>
      <el-form-item align="right">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('formData')">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import * as api from '@/api/user'
export default {
  // 接收父组件传递的属性
  props: {
    userId: null, // 用户id
    visible: {
      //弹出隐藏
      type: Boolean,
      default: false
    },
    title: {
      // 标题
      type: String,
      default: ''
    },
    remoteClose: Function // 用于关闭窗口
  },

  data() {
    var validateRepPassword = (rule,value,callback) =>{
      if(value !== this.formData.newPassword){
        callback(new Error('两次密码不一致'))
      }else{
        callback()
      }
    }
    return {
      formData: {},
      rules: {
                      newPassword: [
                          {required: true, message: '新密码不能为空', trigger: 'blur'},
                          {min: 6, max: 30, message: '长度在 6 到 40 个字符', trigger: 'blur'}
                      ],
                      repPassword: [
                          {required: true, message: '确认密码不能为空', trigger: 'blur'},
                          {validator: validateRepPassword, trigger: 'blur'}
                      ]
                  }
    };
  },
  methods: {
    // 关闭弹窗
    handleClose(done) {
      this.$refs['formData'].resetFields()
      this.remoteClose()
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid)=>{
        if(valid){
          this.formData.userId = this.userId
          api.updatePassword(this.formData).then(response =>{
            if(response.code === 20000){
              this.$message({
                message:'修改成功',
                type:'success',
              })
              this.handleClose()
            }else{
              this.$message({
                message:response.message,
                type:'error'
              })
            }
          })
        }else{
          return false
        }
      })
    }
  }
};
</script>

<style></style>
